package com.news.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.news.dao.UserDao;
import com.news.dao.impl.UserDaoImpl;
import com.news.entity.User;
import com.news.exception.UserBCZException;
import com.news.exception.UserPwdException;
 
@WebServlet("/user/*")
public class UserServlet extends HttpServlet {
	 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		String url=request.getRequestURL().toString();
//		System.out.println("url:"+url);
		String uri=request.getRequestURI();
		System.out.println("uri:"+uri);
		System.out.println("path:"+request.getContextPath());
		String start=request.getContextPath()+"/user/";
		String path=uri.replace(start, "");
		System.out.println("目标路径："+path);
		switch(path) {
		case "login":login(request,response);break;
		case "logout":System.out.println("退出操作");break;
		case "update":System.out.println("更新操作");break;
		}
		
	} 
	protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("pwd");
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		UserDao userdao = new UserDaoImpl();

		try {
			user = userdao.checkUser(user);
		//	out.print("来自" + user.getFrom() + "用户" + user.getUsername() + "登录成功");
//成功后，应该进入首页
			request.getRequestDispatcher("/WEB-INF/manager.jsp").forward(request, response);
//失败后，应该回到登录页，并显示一下错误内容
		} catch (UserBCZException e) {
			//out.print("用户名不存在");
			request.getRequestDispatcher("/login.jsp").include(request, response);
		} catch (UserPwdException e) {
			//out.print("密码错误");
			request.getRequestDispatcher("/login.jsp").include(request, response);
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 	doGet(request, response);
	}

}
